package org.example;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

/**
 * Hello world!
 */
public class AppQuartz {
    public static void main(String[] args) throws Exception {
        System.out.println("Hello World!");
        Scheduler scheduler = new StdSchedulerFactory().getScheduler();
        scheduler.start();

        String cronExpress = "0/5 * * * * ?";//每5秒执行一次
        CronTrigger trigger =
                new CronTrigger(
                        "triggerName11",
                        "triggerGroup11",
                        cronExpress);

        JobDetail detail =
                new JobDetail(
                        "jobName11",
                        "jobGroup11",
                        TimerJob.class);//autofix()方法结尾
        detail.getJobDataMap().put("jobId", 115L);
        detail.getJobDataMap().put("cronexp", cronExpress);
        scheduler.scheduleJob(detail, trigger);

        String cronExpress2 = "0/7 * * * * ?";//每7秒执行一次
        CronTrigger trigger2 =
                new CronTrigger(
                        "triggerName22",
                        "triggerGroup22",
                        cronExpress2);

        JobDetail detail2 =
                new JobDetail(
                        "jobName11",
                        "jobGroup22",
                        TimerJob.class);//autofix()方法结尾
        detail2.getJobDataMap().put("jobId", 117L);
        detail2.getJobDataMap().put("cronexp", cronExpress2);
        scheduler.scheduleJob(detail2, trigger2);




        Thread.sleep(1000 * 16);
        System.out.println("马上删除任务了");
        //注意删除的时候,jobName和groupName必须与调度的时候的完全一致
        scheduler.deleteJob("jobName11", "jobGroup11");
    }

    public static class TimerJob implements Job {
        public TimerJob() {
            System.out.println("TimerJob构造函数被调用-------"+this.hashCode());
        }

        @Override
        public void execute(JobExecutionContext context) throws JobExecutionException {
            JobDetail jobDetail = context.getJobDetail();

            Trigger trigger = context.getTrigger();

            //获取触发器的cron表达式
            if (trigger instanceof CronTrigger) {
                CronTrigger cronTrigger = (CronTrigger) trigger;
                String cronExpression = cronTrigger.getCronExpression();
                System.out.println("cronExpression: " + cronExpression);
            }

            Long jobId = jobDetail.getJobDataMap().getLong("jobId");
            System.out.println("jobID: " + jobId + " 任务被quartz触发.------ " + jobDetail.getGroup());
            System.out.println();
        }
    }
}
